package com.fowo.api.service.impl;


import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.controller.amazon.pdfEntity;
import com.fowo.api.entity.*;
import com.fowo.api.model.transaction.report.management.upload.records.TransactionReportManagementUploadRecordsVo;
import com.fowo.api.model.transaction.report.reconciliation.TransactionReportReconciliationVo;
import com.fowo.api.service.*;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.util.LocalDateUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import org.apache.pdfbox.text.TextPosition;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class AmazonSettlementReportSummaryServiceImpl {

    @Resource
    private ShopInfoServiceImpl ShopInfoServiceImpl;
    @Resource
    protected FileService fileService;
    @Resource
    private AmazonSettlementReportTransManageServiceImpl amazonSettlementReportTransManageService;
    @Resource
    protected AmazonSettlementReportTransManageItemServiceImpl amazonSettlementReportTransManageItemService;
    @Resource
    private AmazonSettlementReportServiceImpl amazonSettlementReportService;
    @Resource
    private TransactionReportReconciliationServiceImpl transactionReportReconciliationService;

    @Resource
    private SysRegionServiceImpl sysRegionService;

    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private TransactionReportManagementUploadRecordsService transactionReportManagementUploadRecordsService;

    private ExecutorService threadPool= Executors.newFixedThreadPool(10);
    @Resource
    private AmazonFinancialEventGroupServiceImpl amazonFinancialEventGroupService;


    @Transactional(rollbackFor = Exception.class)
    public void analysisPdf(SysFile sysFile,String data) throws Exception {
        TransactionReportManagementUploadRecordsVo uploadRecords=new TransactionReportManagementUploadRecordsVo();
        //解析名称
        AmazonSettlementReportTransManage amazonSettlementReportTransManage = extracted(sysFile, data,uploadRecords);
        PDDocument pdDocument =null;
        List<AmazonSettlementReportTransManageItem> smallProject=null;

        try {
             pdDocument=readpdfFile(sysFile);
             getMaxProject(pdDocument,amazonSettlementReportTransManage);
             smallProject = getSmallProject(pdDocument, amazonSettlementReportTransManage);
             checkPrice(amazonSettlementReportTransManage,smallProject);
            uploadRecords.setAnalysisResults("解析成功");
        }catch (Exception e){
            e.printStackTrace();
            uploadRecords.setAnalysisResults("解析失败");
        }finally {
            try {
                pdDocument.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        //保存上传记录
        transactionReportManagementUploadRecordsService.create(uploadRecords);
        if(uploadRecords.getAnalysisResults().equals("解析成功")){
            amazonSettlementReportTransManage.setState("2");
            List<SysFile> files=new ArrayList();
            files.add(sysFile);
            amazonSettlementReportTransManage.setSummaryReport(files);
            amazonSettlementReportTransManage.setUploadTime(new Date());
            //保存
            amazonSettlementReportTransManageService.updateById(amazonSettlementReportTransManage);
            amazonSettlementReportTransManageItemService.remove(Wrappers.<AmazonSettlementReportTransManageItem>lambdaQuery()
                    .eq(AmazonSettlementReportTransManageItem::getParentAmazonSettlementReportTransManage,amazonSettlementReportTransManage.getId()));
            amazonSettlementReportTransManageItemService.saveBatch(smallProject);
            //新增账单
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        addduizhang(amazonSettlementReportTransManage);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }

    }

    private void addduizhang(AmazonSettlementReportTransManage amazonSettlementReportTransManage) throws Exception {
        TransactionReportReconciliation standard = transactionReportReconciliationService.getOne(Wrappers.
                <TransactionReportReconciliation>lambdaQuery()
                .eq(TransactionReportReconciliation::getStore, amazonSettlementReportTransManage.getShopId())
                .eq(TransactionReportReconciliation::getReportType, amazonSettlementReportTransManage.getAccountType()));

        String billingTimestring = amazonSettlementReportTransManage.getBillingTimestring();
        LocalDate localDate = LocalDateUtils.toLocalDate(billingTimestring, "yyyy-MM");
        //获取当月第一天
        Date firstDayOfMonth = LocalDateUtils.firstDayOfMonth( Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant()));
        //获取当月最后一天
        Date lastDayOfMonth = LocalDateUtils.lastDayOfYear( Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant()));

        String startformatString = LocalDateUtils.format(firstDayOfMonth, "yyyy-MM-dd")+" 00:00:00";
        String endformatString = LocalDateUtils.format(lastDayOfMonth, "yyyy-MM-dd")+" 23:59:59";




        //解析的数据
        BigDecimal summaryincome = amazonSettlementReportTransManage.getSummaryincome();
        BigDecimal Summaryexpenses =amazonSettlementReportTransManage.getSummaryexpenses();
        BigDecimal summarytransfers =amazonSettlementReportTransManage.getSummarytransfers();
        BigDecimal summarytax = amazonSettlementReportTransManage.getSummarytax();
        //数据获取转账的
        QueryWrapper<AmazonFinancialEventGroup> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("sum(converted_total) as converted_total");
        queryWrapper.eq("sid",amazonSettlementReportTransManage.getShopId());
        queryWrapper.eq("report_type",amazonSettlementReportTransManage.getShopId());
        queryWrapper.between("fund_transfer_date",startformatString,endformatString);
        //转账金额
        AmazonFinancialEventGroup one = amazonFinancialEventGroupService.getOne(queryWrapper);

//convertedTotal

        if(standard==null){
            TransactionReportReconciliationVo    transactionReportReconciliation=new TransactionReportReconciliationVo();
            transactionReportReconciliation.setReportType(amazonSettlementReportTransManage.getAccountType());
            transactionReportReconciliation.setStore(amazonSettlementReportTransManage.getShopId());
            //station
            transactionReportReconciliation.setStation(amazonSettlementReportTransManage.getCountryId());
            transactionReportReconciliation.setReportingInterval(amazonSettlementReportTransManage.getBillingTimestring());
            //对账结果
            transactionReportReconciliation.setReconciliationResults("");

            if(one.getConvertedTotal().compareTo(summarytransfers)==0){
                //revenue
                transactionReportReconciliation.setRevenue(new BigDecimal("0"));
            }else{

            }


            transactionReportReconciliationService.create(transactionReportReconciliation);
        }else{



            transactionReportReconciliationService.updateById(standard);
        }



    }

    private void checkPrice(AmazonSettlementReportTransManage amazonSettlementReportTransManage, List<AmazonSettlementReportTransManageItem> smallProject) {
        BigDecimal summaryincome = amazonSettlementReportTransManage.getSummaryincome();
        BigDecimal summaryexpenses = amazonSettlementReportTransManage.getSummaryexpenses();
        BigDecimal summarytransfers = amazonSettlementReportTransManage.getSummarytransfers();
        BigDecimal summarytax = amazonSettlementReportTransManage.getSummarytax();
        //筛选smallProject  Maxname  amount求和
        BigDecimal income = smallProject.stream().filter(item -> item.getMaxname().equals("Income")).map(x -> x.getAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal expenses = smallProject.stream().filter(item -> item.getMaxname().equals("Expenses")).map(x -> x.getAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal transfers = smallProject.stream().filter(item -> item.getMaxname().equals("Transfers")).map(x -> x.getAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal tax = smallProject.stream().filter(item -> item.getMaxname().equals("Tax")).map(x -> x.getAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
        Assert.isTrue(summaryincome.compareTo(income)==0,"Income价格不匹配");
        Assert.isTrue(summaryexpenses.compareTo(expenses)==0,"expenses价格不匹配");
        Assert.isTrue(summarytransfers.compareTo(transfers)==0,"transfers价格不匹配");
        Assert.isTrue(summarytax.compareTo(tax)==0,"tax价格不匹配");

    }

    private List<AmazonSettlementReportTransManageItem> getSmallProject(PDDocument pdDocument, AmazonSettlementReportTransManage amazonSettlementReportTransManage) throws IOException {
        Map<String, List<String>> map = getMap();
        List<AmazonSettlementReportTransManageItem> AmazonSettlementReportTransManageItemList=new ArrayList<>();
        //一般for循环map
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<String> value = entry.getValue();
            for (String s : value) {
                BigDecimal bjD = analysisPdfHandle(pdDocument, s, key, "Debits");
                AmazonSettlementReportTransManageItem debits = extracted(s, key, "Debits", bjD,amazonSettlementReportTransManage.getId());
                BigDecimal bjC = analysisPdfHandle(pdDocument, s, key, "Credits");
                AmazonSettlementReportTransManageItem credits =  extracted(s,key,"Credits",bjC,amazonSettlementReportTransManage.getId());
                AmazonSettlementReportTransManageItemList.add(debits);
                AmazonSettlementReportTransManageItemList.add(credits);
            }
        }
        return AmazonSettlementReportTransManageItemList;
    }

    private  AmazonSettlementReportTransManageItem extracted(String s,String key,String type,BigDecimal bj,Long parentId) {
        AmazonSettlementReportTransManageItem AmazonSettlementReportTransManageItem=new AmazonSettlementReportTransManageItem();
        AmazonSettlementReportTransManageItem.setParentAmazonSettlementReportTransManage(parentId);
        AmazonSettlementReportTransManageItem.setName(s);
        AmazonSettlementReportTransManageItem.setAmount(bj);
        AmazonSettlementReportTransManageItem.setMaxname(key);
        AmazonSettlementReportTransManageItem.setType(type);
        return AmazonSettlementReportTransManageItem;
    }

    private void getMaxProject(PDDocument pdDocument,AmazonSettlementReportTransManage  amazonSettlementReportTransManage) {
         String[] rows = null;
        try {
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(true);
            stripper.setStartPage(1);
            stripper.setEndPage(1);
            stripper.setWordSeparator("#");
            stripper.setLineSeparator("\n");
            String text = stripper.getText(pdDocument);
            rows = text.split("\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        amazonSettlementReportTransManage.setSummaryincome(new BigDecimal(rows[7].split("#")[2].replaceAll(",", "")));
        amazonSettlementReportTransManage.setSummaryexpenses(new BigDecimal(rows[8].split("#")[2].replaceAll(",", "")));
        amazonSettlementReportTransManage.setSummarytax(new BigDecimal(rows[9].split("#")[2].replaceAll(",", "")));
        amazonSettlementReportTransManage.setSummarytransfers(new BigDecimal(rows[10].split("#")[2].replaceAll(",", "")));
        BigDecimal Amount = amazonSettlementReportTransManage.getSummaryincome()
                .add(amazonSettlementReportTransManage.getSummaryexpenses())
                .add(amazonSettlementReportTransManage.getSummarytax())
                .add(amazonSettlementReportTransManage.getSummarytransfers());
        amazonSettlementReportTransManage.setAmount(Amount);
    }

    private PDDocument  readpdfFile(SysFile sysFile) throws IOException {
        InputStream read = fileService.read(sysFile);
        //解析pdf文件
        PDDocument pdfDocument = PDDocument.load(read);
        return pdfDocument;
    }

    private BigDecimal analysisPdfHandle(PDDocument document,String projectName,String maxTerm,String type) throws IOException {
        List<pdfEntity> pdfEntityList=new ArrayList<>();
        PDFTextStripperByArea stripper = new PDFTextStripperByArea() {
            @Override
            protected void writeString(String str, List<TextPosition> textPositions) {
                pdfEntity pdfEntity=new pdfEntity();
                pdfEntity.setName(str);
                pdfEntity.setX(textPositions.get(textPositions.size()-1).getX());
                pdfEntity.setY(textPositions.get(textPositions.size()-1).getY());
                pdfEntityList.add(pdfEntity);
            }
        };

        stripper.addRegion("searchArea", new Rectangle2D.Double(0, 0, document.getPage(0).getBBox().getWidth(), document.getPage(0).getBBox().getHeight()));
        stripper.extractRegions(document.getPage(0));

        stripper.setSortByPosition(true);
        stripper.getText(document);
        pdfEntity income = getJiefangX(maxTerm, pdfEntityList,type);
        BigDecimal daiFang = getDaiFang(projectName, pdfEntityList,income);
        return daiFang;
    }
    //获取Product sales (non-FBA) 的贷方
   public static  BigDecimal getDaiFang(String name,List<pdfEntity> pdfEntityList,pdfEntity pdfEntityX){
       pdfEntity pdfEntity = pdfEntityList.stream().filter(x -> x.getName().equals(name)).collect(Collectors.toList()).get(0);
       //判断2个数之间不能相差10  可能大于可能小于
       List<pdfEntity> collect = pdfEntityList.stream().filter(x ->  Math.abs(x.getY() - pdfEntity.getY())< 5.0f).collect(Collectors.toList());
       List<pdfEntity> collect2 = collect.stream().filter(x ->Math.abs(x.getX() - pdfEntityX.getX())< 5.0f).collect(Collectors.toList());
       if(!collect2.isEmpty()){
           pdfEntity pdfEntity1 = collect2.get(0);
           String s = pdfEntity1.getName().replaceAll(",", "");
           return new BigDecimal(s);
       }{
           return new BigDecimal("0");
       }
    }

    private static pdfEntity getJiefangX(String name, List<pdfEntity> pdfEntityList,String type) {
        List<pdfEntity> debits = pdfEntityList.stream().filter(x -> x.getName().equals(type)).collect(Collectors.toList());
        //按照属性 x+y 的合 排序
        debits.sort((o1, o2) -> {
            BigDecimal x1 = new BigDecimal(o1.getX());
            BigDecimal x2 = new BigDecimal(o2.getX());
            BigDecimal y1 = new BigDecimal(o1.getY());
            BigDecimal y2 = new BigDecimal(o2.getY());
            return x1.add(y1).compareTo(x2.add(y2));
        });

        if(name.equals("Income")){
           return debits.get(0);
        }else if(name.equals("Transfers")){
            return debits.get(1);
        }else if(name.equals("Expenses")){
            return debits.get(2);
        }else if(name.equals("Tax")){
            return debits.get(3);
        }
        return null;
    }

    public Map<String, List<String>> getMap() {
        Map<String, List<String>> map = new HashMap<>();
        List<String> IncomeList =new ArrayList<>();
        IncomeList.add("Product sales (non-FBA)");
        IncomeList.add("Product sale refunds (non-FBA)");
        IncomeList.add("FBA product sales");
        IncomeList.add("FBA product sale refunds");
        IncomeList.add("FBA inventory credit");
        IncomeList.add("FBA liquidation proceeds");
        IncomeList.add("FBA Liquidations proceeds adjustments");
        IncomeList.add("Shipping credits");
        IncomeList.add("Shipping credit refunds");
        IncomeList.add("Gift wrap credits");
        IncomeList.add("Gift wrap credit refunds");
        IncomeList.add("Promotional rebates");
        IncomeList.add("Promotional rebate refunds");
        IncomeList.add("A-to-z Guarantee claims");
        IncomeList.add("Chargebacks");
        IncomeList.add("Amazon Shipping Reimbursement");
        IncomeList.add("SAFE-T reimbursement");
        map.put("Income", IncomeList);
        List<String> ExpensesList =new ArrayList<>();
        ExpensesList.add("Seller fulfilled selling fees");
        ExpensesList.add("FBA selling fees");
        ExpensesList.add("Selling fee refunds");
        ExpensesList.add("FBA transaction fees");
        ExpensesList.add("FBA transaction fee refunds");
        ExpensesList.add("Other transaction fees");
        ExpensesList.add("Other transaction fee refunds");
        ExpensesList.add("FBA inventory and inbound services fees");
        ExpensesList.add("Shipping label purchases");
        ExpensesList.add("Shipping label refunds");
        ExpensesList.add("Carrier shipping label adjustments");
        ExpensesList.add("Service fees");
        ExpensesList.add("Refund administration fees");
        ExpensesList.add("Adjustments");
        ExpensesList.add("Cost of Advertising");
        ExpensesList.add("Refund for Advertiser");
        ExpensesList.add("Liquidations fees");
        map.put("Expenses", ExpensesList);
        List<String> TransfersList =new ArrayList<>();
        TransfersList.add("Transfers to bank account");
        TransfersList.add("Failed transfers to bank account");
        TransfersList.add("Disburse to Amazon Gift Card balance");
        TransfersList.add("Charges to credit card and other debt recovery");
        map.put("Transfers", TransfersList);
        List<String> TaxList =new ArrayList<>();
        TaxList.add("Product, shipping, gift wrap taxes and regulatory fee collected");
        TaxList.add("Product, shipping, gift wrap taxes and regulatory fee refunded");
        TaxList.add("Amazon Obligated Tax and Regulatory Fee Withheld");
        map.put("Tax", TaxList);
        return map;
    }


    private AmazonSettlementReportTransManage extracted(SysFile sysFile,String data,TransactionReportManagementUploadRecordsVo uploadRecords) {

            String filename = sysFile.getFilename().substring(0, sysFile.getFilename().lastIndexOf("."));
            //下划线_ 拆分 32#-Ieftop-US-US_US_Standard
            String[] split = filename.split("_");
            Assert.isTrue(split.length==3, "名称格式错误");
            ShopInfo one = ShopInfoServiceImpl.getOne(Wrappers.<ShopInfo>lambdaQuery().eq(ShopInfo::getShopName, split[0])
                    .eq(ShopInfo::getRegion, split[1]));
            Assert.notNull(one, "店铺不存在");
            //split[2]  后缀.pdf 去掉

        AmazonSettlementReportTransManage one1 = amazonSettlementReportTransManageService.getOne(Wrappers.<AmazonSettlementReportTransManage>lambdaQuery()
                .eq(AmazonSettlementReportTransManage::getShopId, one.getId())
                .eq(AmazonSettlementReportTransManage::getBillingTimestring, data)
                .eq(AmazonSettlementReportTransManage::getAccountType, split[2]));
        Assert.notNull(one1, "对账店铺不存在");
        uploadRecords.setSid(one1.getId());
        LocalDate localDate = LocalDateUtils.toLocalDate(data, LocalDateUtils.DATE_PATTERN1);
        uploadRecords.setBillingTime(Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        uploadRecords.setReportType(split[2]);
        uploadRecords.setSite(one.getMid());
        uploadRecords.setUploadTime(new Date());
        return one1;
    }

    //获取当月的对账的数据
    public void getShop() throws Exception {

        String startDate=LocalDateUtils.format(LocalDateUtils.firstDayOfMonth(new Date()),LocalDateUtils.DATE_PATTERN)+" 00:00:00";
        String endDate=LocalDateUtils.format(LocalDateUtils.lastDayOfMonth(new Date()),LocalDateUtils.DATE_PATTERN)+" 00:00:00";
        QueryWrapper<AmazonSettlementReport> queryWrapper = new QueryWrapper();
        queryWrapper.select("sid,account_type,currency");
        queryWrapper.between("posted_date_time", startDate, endDate);
        queryWrapper.groupBy("sid,account_type");
        List<AmazonSettlementReport> list = amazonSettlementReportService.list(queryWrapper);
//        List<AmazonSettlementReportTransManage> AmazonSettlementReportTransManageList=new ArrayList<>();
        for(int i=0;i<list.size();i++){
            AmazonSettlementReport amazonSettlementReport = list.get(i);
            AmazonSettlementReportTransManage one = amazonSettlementReportTransManageService.getOne(Wrappers.
                    <AmazonSettlementReportTransManage>lambdaQuery()
                    .eq(AmazonSettlementReportTransManage::getShopId, amazonSettlementReport.getSid())
                    .eq(AmazonSettlementReportTransManage::getAccountType, amazonSettlementReport.getAccountType())
            );
            if(one==null){
                AmazonSettlementReportTransManage   amazonSettlementReportTransManage=new AmazonSettlementReportTransManage();
                amazonSettlementReportTransManage.setShopId(amazonSettlementReport.getSid());
                ShopInfo byId = ShopInfoServiceImpl.getById(amazonSettlementReport.getSid());
                SysRegion one1 = sysRegionService.getOne(Wrappers.<SysRegion>lambdaQuery()
                        .eq(SysRegion::getName, byId.getCountry())
                        .eq(SysRegion::getPlatform,"Amazon"));
                amazonSettlementReportTransManage.setCountryId(one1.getId());

                //accountType
                amazonSettlementReportTransManage.setAccountType(amazonSettlementReport.getAccountType());
                amazonSettlementReportTransManage.setState("0");
                amazonSettlementReportTransManage.setCurrency(amazonSettlementReport.getCurrencyCode());
                amazonSettlementReportTransManage.setBillingTime(new Date());
                amazonSettlementReportTransManage.setBillingTimestring(LocalDateUtils.format(LocalDateUtils.firstDayOfMonth(new Date()),LocalDateUtils.DATE_PATTERN1));
                amazonSettlementReportTransManageService.save(amazonSettlementReportTransManage);
            }


        }


    }


    public void download(IdListPo po, HttpServletResponse response) throws IOException {
        List<AmazonSettlementReportTransManage> list = amazonSettlementReportTransManageService.list(Wrappers.<AmazonSettlementReportTransManage>lambdaQuery()
                .in(AmazonSettlementReportTransManage::getId, po.getIds()));

        List<SysFile> filePaths = new ArrayList<>();
       //for循环list
        for(int i=0;i<list.size();i++){
            AmazonSettlementReportTransManage amazonSettlementReportTransManage = list.get(i);
            if(amazonSettlementReportTransManage.getSummaryReport()!=null&&amazonSettlementReportTransManage.getSummaryReport().size()>0){
                filePaths.addAll(amazonSettlementReportTransManage.getSummaryReport());
            }
        }
        response.addHeader("Content-Disposition", "attachment; filename=\"batch.zip\"");
        AmazonSettlementReportTransManage amazonSettlementReportTransManage = list.get(0);
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
            for (SysFile filePath : filePaths) {
                addToZip(zipOutputStream, filePath);
            }
        }
    }
    private void addToZip(ZipOutputStream zipOutputStream, SysFile filePath) throws IOException {
        try (InputStream inputStream = fileService.read(filePath)) {
            ZipEntry zipEntry = new ZipEntry(Objects.requireNonNull(filePath.getFilename()));
            zipOutputStream.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = inputStream.read(bytes)) >= 0) {
                zipOutputStream.write(bytes, 0, length);
            }
        }
    }



//    public   void kawajisuanfa(){
//        String param = "(\"Principal\",\"ShippingCharge\", \"ShippingDiscount\", \"GiftWrap\", \"PromotionDiscount\", \"REVERSAL_REIMBURSEMENT\", \"FREE_REPLACEMENT_REFUND_ITEMS\", \"WAREHOUSE_DAMAGE\")";
//        String greatValue=null;
//        String greatValue1=null;
//        String greatValue2=null;
//        List<Map<String, Object>> maps = jdbcTemplate
//                .queryForList("select FORMAT(SUM(金额),2) 金额,交易类型 FROM sheet20 where 报告类型='Standard' and 交易类型 not in ('GiftWrapTax') " +
//                        "GROUP BY 交易类型\n");
//        List<entity11> list = JSON.parseArray(JSON.toJSONString(maps),entity11.class);
//
//        greatValue = getGreatValue(list, 144390.90, 0.00);
//        System.out.println(greatValue);
//    }

//    public String  getGreatValue(List<entity11> list,Double target,Double requirement){
//        JSONObject result=new JSONObject();
//        Set<Double> price=new HashSet();
//        try{
//            double lapse = 1000;
//            Random random = new Random();
//            for (int i=0;i<100000000;i++) {
//                int numsize = random.nextInt(list.size()  + 1);
//                List<Map<String,Object>> ares = new ArrayList<Map<String,Object>>();
//                HashMap<Integer,Integer> map = new HashMap<>();
//                double thissum = 0;
//                for (int j=0 ;j<numsize;j++){
//                    int anumberindex = random.nextInt(list.size());
//                    while (map.containsKey(anumberindex))
//                    {
//                        anumberindex = random.nextInt(list.size());
//                    }
//                    entity11 entity11 = list.get(anumberindex);
//                    map.put(anumberindex,1);
//                    HashMap<String, Object> obj = new HashMap<String,Object>();
//                    obj.put("id", entity11.getId());
//                    obj.put("交易类型",entity11.get交易类型());
//                    obj.put("金额", entity11.get金额());
//                    ares.add(obj);
//                    thissum += entity11.get金额();
//                }
//                if(Math.abs(thissum - target)<lapse){
//                    lapse = Math.abs(thissum - target);
//                }
//                price.add(lapse);
//                if(Double.compare(lapse,requirement)==requirement){
//                    result.put("data", JSON.toJSON(ares));
//                    result.put("count", thissum);
//                    result.put("litter", Math.abs(thissum - target));
//                    break;
//                }
//
//            }
//        }catch(Exception e){
//            e.printStackTrace();
//        }
//        if(result.size()==0){
//            Optional<Double> min = price.stream().min(Comparator.comparing(u -> u));
//            min.ifPresent(aDouble -> result.put("price", aDouble));
//        }
//        return result.toString();
//    }

    @Transactional(rollbackFor =  Exception.class)
    public void batchDelete(IdListPo po, HttpServletResponse response) {

        List<AmazonSettlementReportTransManage> list = amazonSettlementReportTransManageService.list(Wrappers.<AmazonSettlementReportTransManage>lambdaQuery()
                .in(AmazonSettlementReportTransManage::getId, po.getIds()));
        //判断交易对账是否对账
        for(int i=0;i<list.size();i++){
            AmazonSettlementReportTransManage amazonSettlementReportTransManage = list.get(i);
            if(amazonSettlementReportTransManage.getState().equals("0")){
                continue;
            }

            TransactionReportReconciliation one = transactionReportReconciliationService.getOne(Wrappers.
                    <TransactionReportReconciliation>lambdaQuery()
                    .eq(TransactionReportReconciliation::getStore, amazonSettlementReportTransManage.getShopId())
                    .eq(TransactionReportReconciliation::getReportType, amazonSettlementReportTransManage.getAccountType())
                    .eq(TransactionReportReconciliation::getReportingInterval, amazonSettlementReportTransManage.getBillingTime())
            );
            if(one!=null){
                if(one.getReconciliationResults().equals("2")){
                    continue;
                }
                //删除
                amazonSettlementReportTransManageService.removeById(amazonSettlementReportTransManage.getId());
            }


            //删除子表
            amazonSettlementReportTransManageItemService.remove(Wrappers.<AmazonSettlementReportTransManageItem>lambdaQuery().eq(AmazonSettlementReportTransManageItem::getParentAmazonSettlementReportTransManage,amazonSettlementReportTransManage.getId()));
        }


    }
}
